import axios from "axios";
import { ElMessage } from "element-plus";
import { getToken, removerUser } from "./user";
import router from "@/router";
axios.defaults.baseURL = import.meta.env.VITE_BASE_URL;
axios.defaults.timeout = 8000;

// 拦截器
axios.interceptors.request.use((config) =>{
  if (getToken()) {
    config.headers.Authorization = getToken();
  }
  return config;
}, (err) => {Promise.reject(err)})

axios.interceptors.response.use((res) => {
  // 校验 token是否过期 或者 未登录
  switch (res.data.code) {
    case 401:
      removerUser();
      ElMessage({
        type: "error",
        message: "token过期，请重新登录",
        onClose: () => {
          router.replace('/login')
        }
      });
     
      break;
    case 403:
      ElMessage({
        type: "error",
        message: "用户未登录",
        onClose: () => {
          router.replace('/login')
        }
      });
      break;
    default:
      break;
  }
  return res.data;
}, (err) => {Promise.reject(err)})

export default axios;